package pers.corvey.studyjava.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import pers.corvey.studyjava.model.User;
import pers.corvey.studyjava.model.form.LoginForm;
import pers.corvey.studyjava.model.json.ServerMessageJson;
import pers.corvey.studyjava.service.CaptchaService;
import pers.corvey.studyjava.service.UserService;
import pers.corvey.studyjava.util.CookieUtils;

@Controller
@RequestMapping("/sessions")
public class SessionController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private CaptchaService captchaService;
    
    @GetMapping
    @ResponseBody
    public ServerMessageJson get(HttpSession session) {
        ServerMessageJson messageJson = new ServerMessageJson();
        String userId = (String) session.getAttribute("userId");
        if (userId != null) {
            messageJson.setMessage("已登录");
        } else {
            messageJson.setMessage("请先登录！");
        }
        return messageJson;
    }
    
    @PostMapping
    @ResponseBody
    public Map<String, Object> create(LoginForm loginForm, HttpSession session) {
        loginForm.validate();
        String correctCaptcha = (String) session.getAttribute("captcha");
        captchaService.checkCaptcha(correctCaptcha, loginForm.getCaptcha());
        User user = loginForm.toUser(); 
        user = userService.login(user);
        session.removeAttribute("captcha");
        session.setAttribute("userId", user.getId());
        Map<String, Object> json = new HashMap<>();
        json.put("userName", user.getName());
        return json;
    }
    
    @DeleteMapping
    @ResponseBody
    public void delete(HttpSession session, HttpServletResponse response) {
        CookieUtils.removeCookieByName(response, "userName");
        session.removeAttribute("userId");
    }
    
}
